package com.example.demo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.custom.AjaxResult;
import com.example.demo.custom.BaseController;
import com.example.demo.entity.Permission;
import com.example.demo.entity.TbMenu;
import com.example.demo.form.TbMenuForm;
import com.example.demo.security.UserUtils;
import com.example.demo.service.PermissionService;
import com.example.demo.service.TbMenuService;

@Controller
@RequestMapping(value = "/menu")
public class TbMenuController extends BaseController<TbMenu, Integer, TbMenuForm> {
	@Autowired
	private TbMenuService service;

	@Autowired
	private UserUtils userUtils;
	@Autowired
	private PermissionService permissionService;

	@RequestMapping(value = "/combotree")
	@ResponseBody
	public Object combotree(Integer id) {
		List<TbMenu> list = service.findByParentIsNull();
		return buildTree(list, id);
	}

	private List<HashMap<String, Object>> buildTree(List<TbMenu> list, Integer id) {
		List<HashMap<String, Object>> result = new ArrayList<>();
		for (TbMenu menu : list) {
			if (menu.getId() != id) {
				HashMap<String, Object> node = new HashMap<>();
				node.put("id", menu.getId());
				node.put("name", menu.getName());
				node.put("parentId", menu.getParentId());
				node.put("url", menu.getUrl());
				node.put("Permission", menu.getRole());
				node.put("icon", menu.getIcon());
				node.put("idx1", menu.getIdx1());
				if (!menu.getChildren().isEmpty()) {
					node.put("nodes", buildTree(menu.getChildren(), id));
				}
				result.add(node);
			}
		}
		return result;
	}

	@Override
	public Object save(TbMenuForm form) {
		Integer roleId = form.getRoleId();
		if (roleId != null) {
			form.setRole(new Permission(roleId));
		} else {
			form.setRole(null);
		}
		Integer parentId = form.getParentId();
		if (parentId != null) {
			form.setParent(new TbMenu(parentId));
		} else {
			form.setParent(null);
		}
		return super.save(form);
	}

	@Override
	public void edit(TbMenuForm form, ModelMap modelMap) throws InstantiationException, IllegalAccessException {
		TbMenu model = new TbMenu();
		Integer id = form.getId();
		if (id == null) {
			if (form.getParentId() != null) {
				model.setParent(new TbMenu(form.getParentId()));
			}
		} else {
			model = service.findById(id);
		}
		modelMap.put("model", model);
	}

	/**
	 * @return 通过人员返回相应页面
	 */
	@RequestMapping(value = "/findbyuser")
	@ResponseBody
	public Object findbyuser(Integer id) {
		List<TbMenu> menus = service.findAuditMenu();
		return buildTree(menus, id);
	}
}
